package com.example.userinfoservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;


import com.example.blogcommon.constant.Constants;
import com.example.blogcommon.exception.BlogException;
import com.example.blogcommon.pojo.Result;
import com.example.blogcommon.utils.*;
import com.example.bloginfoapi.BlogServiceApi;
import com.example.bloginfoapi.response.BlogInfoResponse;
import com.example.userinfoapi.request.UserInfoRegisterRequest;
import com.example.userinfoapi.request.UserInfoRequest;
import com.example.userinfoapi.response.UserInfoResponse;
import com.example.userinfoapi.response.UserLoginResponse;
import com.example.userinfoservice.convert.BeanConvert;
import com.example.userinfoservice.dataobject.UserInfo;
import com.example.userinfoservice.mapper.UserInfoMapper;
import com.example.userinfoservice.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserInfoMapper userInfoMapper;
//    @Autowired
//    private BlogMapper blogMapper;

    @Autowired
    private BlogServiceApi blogServiceApi;

    @Autowired
    private Redis redis;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public static long EXPIRE_TIME = 14 * 24 * 60 * 60;

    public static String USER_PREFIX = "user";

    @Override
    public UserLoginResponse login(UserInfoRequest user) {
        //验证账号密码是否正确
//        UserInfo userInfo = selectUserInfoByName(user.getUserName());
        UserInfo userInfo = queryUserInfo(user.getUserName());
        if (userInfo==null || userInfo.getId()==null){
            throw new BlogException("用户不存在");
        }

        if (!SecurityUtil.verify(user.getPassword(),userInfo.getPassword())){
            throw new BlogException("用户密码不正确");
        }
        //账号密码正确的逻辑
        Map<String,Object> claims = new HashMap<>();
        claims.put("id", userInfo.getId());
        claims.put("name", userInfo.getUserName());

        String jwt = JWTUtils.genJwt(claims);
        return new UserLoginResponse(userInfo.getId(), jwt);
    }

    @Override
    public UserInfoResponse getUserInfo(Integer userId) {
        UserInfoResponse userInfoResponse = new UserInfoResponse();
        UserInfo userInfo = selectUserInfoById(userId);
        BeanUtils.copyProperties(userInfo, userInfoResponse);
        return userInfoResponse;
    }

    @Override
    public UserInfoResponse selectAuthorInfoByBlogId(Integer blogId) {
        UserInfoResponse userInfoResponse = new UserInfoResponse();
        //1. 根据博客ID, 获取作者ID
//        BlogInfo blogInfo = getBlogInfo(blogId);
        Result<BlogInfoResponse> blogInfoResponse = blogServiceApi.getBlogDeatail(blogId);
        //2. 根据作者ID, 获取作者信息
        if (blogInfoResponse == null || blogInfoResponse.getData() == null){
            throw new BlogException("博客不存在");
        }
        UserInfo userInfo = selectUserInfoById(blogInfoResponse.getData().getUserId());
        BeanUtils.copyProperties(userInfo, userInfoResponse);
        return userInfoResponse;
    }

    @Override
    public Integer register(UserInfoRegisterRequest registerRequest) {
        //参数校验
        checkUserInfo(registerRequest);
        UserInfo userInfo = BeanConvert.convertUserInfoByEncrypt(registerRequest);
        try {
            int insert = userInfoMapper.insert(userInfo);
            if (insert == 1) {
                redis.set(buildKey(userInfo.getUserName()), JsonUtil.toJson(userInfo),EXPIRE_TIME);
                userInfo.setPassword("");
                rabbitTemplate.convertAndSend(Constants.USER_EXCHANGE_NAME,"",JsonUtil.toJson(userInfo));
                return userInfo.getId();
            } else {
                throw new BlogException("用户注册失败");
            }
        } catch (Exception e) {
            log.error("用户注册失败，e：", e);
            throw new BlogException("用户注册失败");
        }

    }

    private String buildKey(String userName) {
        return redis.buildKey(USER_PREFIX,userName);
    }

    private void checkUserInfo(UserInfoRegisterRequest registerRequest) {
        UserInfo userInfo = selectUserInfoByName(registerRequest.getUserName());
        if (userInfo != null) {
            throw new BlogException("用户名已存在");
        }
        //邮箱，url 格式校验
        if (!RegexUtil.checkMail(registerRequest.getEmail())){
            throw new BlogException("邮箱格式错误");
        }
        if (!RegexUtil.checkURL(registerRequest.getGithubUrl())){
            throw new BlogException("url格式错误");
        }
    }

    private UserInfo queryUserInfo(String userName) {
        String key = buildKey(userName);
        boolean exists = redis.hasKey(key);
        if (exists) {
            log.info("从 redis 中获取参数 key {}",key);
            String userJson = redis.get(key);
            UserInfo userInfo = JsonUtil.parseJson(userJson, UserInfo.class);
            return userInfo == null ? selectUserInfoByName(userJson) : userInfo;
        }else {
            log.info("从 mysql 中获取参数");
            return selectUserInfoByName(userName);
        }
    }
    public UserInfo selectUserInfoByName(String userName) {
        return userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getUserName, userName).eq(UserInfo::getDeleteFlag, 0));
    }
    private UserInfo selectUserInfoById(Integer userId) {
        return userInfoMapper.selectOne(new LambdaQueryWrapper<UserInfo>()
                .eq(UserInfo::getId, userId).eq(UserInfo::getDeleteFlag, 0));
    }

}
